package com.github.tommas.admintpl.config;

import com.github.tommas.admintpl.cache.CacheFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
public class CacheFactoryConfiguration {

    @Value("${cache.factory.use-local-cache:false}")
    private boolean useLocalCache;

    @Value("${cache.factory.key-prefix:null}")
    private String keyPrefix;

    @Bean
    CacheFactory cacheFactory(ObjectProvider<RedisConnectionFactory> redisConnectionFactory) {
        RedisConnectionFactory rcf = redisConnectionFactory.getIfAvailable();
        if (useLocalCache || rcf == null) {
            return new CacheFactory();
        }

        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(rcf);
        redisTemplate.setKeySerializer(RedisSerializer.string());
        redisTemplate.setValueSerializer(RedisSerializer.json());

        return new CacheFactory(keyPrefix, redisTemplate);
    }
}
